package com.cloudxingkong.dianyinke.Student.Ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.cloudxingkong.dianyinke.NewTeacher.Adapter.HomeLoopAdapter;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.CookieHelper;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.HttpUtils;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.SysExitUtil;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.THomePicJsonUtils;
import com.cloudxingkong.dianyinke.NewTeacher.config.Constans;
import com.cloudxingkong.dianyinke.R;
import com.cloudxingkong.dianyinke.Student.bean.StudentMessage;
import com.cloudxingkong.dianyinke.Uri.studentUri.StudentUri;
import com.cloudxingkong.dianyinke.Uri.teacherUri.ThisUri;
import com.cloudxingkong.dianyinke.Widgets.MyGridLayout;
import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


/**
 * @文件名 MainActivity
 * @描述 主线程
 * @作者 Zxrui
 * @时间 2016/3/10
 * @版本 1.0
 */
public class MainActivity extends AppCompatActivity implements AMapLocationListener {
	private long exitTime = 0;
	private ViewPager viewPager;
	private List<HashMap<String, String>> data;
	private int mDemoPosition = 0;
	private final int FAKE_DEMO_SIZE = 100;
	private final int DEFAULT_DOT_SIZE = 4;
	private boolean isUserTouched = false;
	private ImageView[] ivDots;
	private Timer timer = new Timer ();
	private HomeLoopAdapter adapter;
	private SharedPreferences sharedPreferences;
	private String sessionid;
	//定位
	private AMapLocationClientOption locationOption = null;
	private AMapLocationClient mlocationClient = null;
	public boolean isGPS = false;

	MyGridLayout grid;
	int[] srcs = {R.mipmap.iconfont_yuyue_2x, R.mipmap.iconfont_kecheng_2x,
			R.mipmap.iconfont_bofang_2x, R.mipmap.iconfont_liwu_2x,
			R.mipmap.iconfont_wode_2x, R.mipmap.iconfont_icon_2x};
	String titles[] = {"我的课程", "预约管理", "视频教学", "积分兑换", "个人中心", "新闻资讯"};

	@Override
	protected void onCreate (Bundle savedInstanceState) {
		super.onCreate (savedInstanceState);
		setContentView (R.layout.activity_main_backup);


		grid = (MyGridLayout) findViewById (R.id.list);
		grid.setGridAdapter (new MyGridLayout.GridAdatper () {

			@Override
			public View getView (int index) {
				View view = getLayoutInflater ().inflate (R.layout.actions_item,
						null);
				ImageView iv = (ImageView) view.findViewById (R.id.iv);
				TextView tv = (TextView) view.findViewById (R.id.tv);
				iv.setImageResource (srcs[index]);
				tv.setText (titles[index]);
				return view;
			}

			@Override
			public int getCount () {
				// TODO Auto-generated method stub
				return titles.length;
			}
		});
		grid.setOnItemClickListener (new MyGridLayout.OnItemClickListener () {

			@Override
			public void onItemClick (View v, int index) {

				switch (index) {
					case 0:
						startActivity (new Intent (MainActivity.this, KeChengYuYue.class));
						break;
					case 1:
						startActivity (new Intent (MainActivity.this, MyAppointment.class));
						break;
					case 2:
						startActivity (new Intent (MainActivity.this, VideoTeaching.class));
						break;
					case 3:
						startActivity (new Intent (MainActivity.this, CreditsExchange.class));
						break;
					case 4:
						startActivity (new Intent (MainActivity.this, PersonalCenter.class));
						break;
					case 5:
						startActivity (new Intent (MainActivity.this, NewsInformation.class));
						break;
					default:
						break;

				}
			}
		});


		SysExitUtil.activityList.add (this);
		mlocationClient = new AMapLocationClient (getApplicationContext ());
		mlocationClient.setLocationListener (this);
		init ();
		loadLocation ();
		isGPSEnabled ();

	}

	private void loadLocation () {
		locationOption = new AMapLocationClientOption ();
		locationOption.setLocationMode (AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
		locationOption.setNeedAddress (true);
		locationOption.setOnceLocation (false);
		locationOption.setWifiActiveScan (true);
		locationOption.setMockEnable (false);
		locationOption.setInterval (Constans.SPLASH_DISPLAY_LENGHT);
		mlocationClient.setLocationOption (locationOption);
		mlocationClient.startLocation ();
	}

	@Override
	public void onLocationChanged (AMapLocation aMapLocation) {
		if (aMapLocation != null) {
			if (aMapLocation.getErrorCode () == 0) {
				aMapLocation.getLocationType ();
				double latitude = aMapLocation.getLatitude ();//纬度
				double longitude = aMapLocation.getLongitude ();//经度
				String address = aMapLocation.getAddress ();//地址
				SharedPreferences.Editor edit = sharedPreferences.edit ();
				edit.putString ("latitude", latitude + "");
				edit.putString ("longitude", longitude + "");
				edit.commit ();

				Log.e ("test", "高德定位地址 " + address + "\naddress inside sp : " + sharedPreferences.getString ("Laddress", ""));
			}
		} else {
			Log.e ("test", "locationError , code = " + aMapLocation.getErrorCode () + "\ninfo " + aMapLocation.getErrorInfo ());
		}
	}


	private void isGPSEnabled () {
		isGPS = HttpUtils.isGPSEnabled (this);
		if (!isGPS) {
			new AlertDialog.Builder (this)
					.setTitle ("提示")
					.setMessage ("检测到您未开启GPS。打开GPS将更方便于附近老师的搜索，是否前去设置打开？")
					.setNegativeButton ("取消", null)
					.setPositiveButton ("好的", new DialogInterface.OnClickListener () {
						@Override
						public void onClick (DialogInterface dialog, int which) {
							Intent intent = new Intent (Settings.ACTION_LOCATION_SOURCE_SETTINGS);
							startActivity (intent);
						}
					}).create ().show ();
		}
	}

	private void qryStudent () {
		sharedPreferences = MainActivity.this.getSharedPreferences ("data_dyk", 0);
		final String sessionid = CookieHelper.getSessionID (sharedPreferences);
		RequestParams params = new RequestParams (ThisUri.SERVER_YUMING + StudentUri.STUDNETMESSAGE);
		params.addHeader ("cookie", sessionid);
		x.http ().get (params, new Callback.CommonCallback<String> () {
			@Override
			public void onSuccess (String result) {
				Log.e ("test", "学生个人信息 " + result);
				if (result != null) {
					Message msg = handler.obtainMessage ();
					msg.what = 1;
					msg.obj = result;
					handler.sendMessage (msg);
				}
			}

			@Override
			public void onError (Throwable ex, boolean isOnCallback) {
				Log.e ("test", "获取学生个人信息失败");
			}

			@Override
			public void onCancelled (CancelledException cex) {

			}

			@Override
			public void onFinished () {

			}
		});
	}

	private Handler handler = new Handler () {
		@Override
		public void handleMessage (Message msg) {
			super.handleMessage (msg);
			switch (msg.what) {
				case 1:
					String state = (String) msg.obj;
					Log.e ("test", "学生信息" + state);
					if (state != null) {
						Gson gson = new Gson ();
						StudentMessage studentMessage = null;
						studentMessage = gson.fromJson (state, StudentMessage.class);
						String studentName = studentMessage.getObj ().getMemname () + "";
						String studentPhone = studentMessage.getObj ().getPhone () + "";
						String studentArrds = studentMessage.getObj ().getAddrs () + "";
						String studentPic = studentMessage.getObj ().getAvatar () + "";

						SharedPreferences.Editor editor = sharedPreferences.edit ();
						editor.putString ("studentName", studentName);
						editor.putString ("studentPhone", studentPhone);
						editor.putString ("arrds", studentArrds);
						editor.putString ("studentPic", studentPic);
						editor.commit ();
					}
					break;
			}
		}
	};

	private void dealWithResponse (String result) {
		data = THomePicJsonUtils.getPathFormJson (result);
		adapter = new HomeLoopAdapter (viewPager, data, this);
		viewPager.setAdapter (adapter);
	}

	private void initHomePiclist () {
		x.http ().get (new RequestParams (ThisUri.SERVER_YUMING + ThisUri.HOME_PIC_LIST), new Callback.CommonCallback<String> () {
			@Override
			public void onSuccess (String result) {
				dealWithResponse (result);
			}

			@Override
			public void onError (Throwable ex, boolean isOnCallback) {

			}

			@Override
			public void onCancelled (CancelledException cex) {

			}

			@Override
			public void onFinished () {

			}
		});
	}

	@Override
	public boolean onKeyDown (int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if ((System.currentTimeMillis () - exitTime) > 2000) {
				Toast.makeText (MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show ();
				exitTime = System.currentTimeMillis ();
			} else {
				System.exit (0);
			}
			return true;
		}
		return false;
	}

	//初始化
	private void init () {
		viewPager = (ViewPager) findViewById (R.id.teach_home_viewpager);

		data = new ArrayList<> ();
		ivDots = new ImageView[]{
				(ImageView) findViewById (R.id.iv_dot1),
				(ImageView) findViewById (R.id.iv_dot2),
				(ImageView) findViewById (R.id.iv_dot3),
				(ImageView) findViewById (R.id.iv_dot4)};

		initHomePiclist ();

		viewPager.setOnTouchListener (new View.OnTouchListener () {
			@Override
			public boolean onTouch (View v, MotionEvent event) {
				int action = event.getAction ();
				if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_HOVER_MOVE) {
					isUserTouched = true;
				} else if (action == MotionEvent.ACTION_UP) {
					isUserTouched = false;
				}
				return false;
			}
		});

		timer.schedule (timerTask, 3000, 3000);
		initEvent ();
	}

	private void initEvent () {
		viewPager.addOnPageChangeListener (new ViewPager.OnPageChangeListener () {
			@Override
			public void onPageScrolled (int position, float positionOffset, int positionOffsetPixels) {

			}

			@Override
			public void onPageSelected (int position) {
				mDemoPosition = position;
				setDot (position);
			}

			@Override
			public void onPageScrollStateChanged (int state) {

			}
		});
	}

	private void setDot (int position) {
		position %= DEFAULT_DOT_SIZE;
		for (ImageView dot : ivDots) {
			dot.setImageResource (R.drawable.dot_normal);
		}
		ivDots[position].setImageResource (R.drawable.dot_focused);
	}


	private TimerTask timerTask = new TimerTask () {
		@Override
		public void run () {
			if (!isUserTouched) {
				mDemoPosition = (mDemoPosition + 1) % FAKE_DEMO_SIZE;
				runOnUiThread (new Runnable () {
					@Override
					public void run () {
						if (mDemoPosition == FAKE_DEMO_SIZE - 1) {
							viewPager.setCurrentItem (DEFAULT_DOT_SIZE - 1, false);
						} else {
							viewPager.setCurrentItem (mDemoPosition);
						}
					}
				});
			}
		}
	};
}
